#include "chatserver.hpp"
#include "json.hpp"
#include "chatservice.hpp"

#include<functional>
#include<iostream>
#include<string>
using namespace std;
using namespace placeholders;
using json = nlohmann::json;

ChatServer::ChatServer(EventLoop*loop,
        const InetAddress&listenAddr,
        const string& nameArg)
        :_server(loop,listenAddr,nameArg)
        ,_loop(loop)
{
    // 注册回调
    _server.setConnectionCallback(std::bind(&ChatServer::onConnection,this,_1));
    _server.setMessageCallback(std::bind(&ChatServer::onMessage,this,_1,_2,_3));
    // 设置线程数量
    _server.setThreadNum(4);

}



// 启动服务
void ChatServer::start()
{
    _server.start();    
}



// 上报连接相关信息的回调函数
void ChatServer::onConnection(const TcpConnectionPtr&conn)
{
    // 用户断开连接，释放资源
    if(!conn->connected()) 
    {
        // 客户端异常关闭
        ChatService::instance()->clientCloseException(conn);
        conn->shutdown(); 
    }
}

// 发送信息的回调
void ChatServer::onMessage(const TcpConnectionPtr&conn,
                Buffer *buffer,
                Timestamp time)

{
    // 从缓冲区读数据
    string buf = buffer->retrieveAllAsString();
    // 数据反序列化
    json js = json::parse(buf);
    // 达到的目的：完全解耦网络模块和业务模块的代码
    // 通过js["msgid"] 获取=》handler =》conn js time 
    auto msgHandler = ChatService::instance()->getHandler(js["msgid"].get<int>());
    // 执行回调
    msgHandler(conn,js,time);
}
